package com.epfresh.supplier.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.epfresh.api.entity.RequestEntityMapSupply;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.entity.Version;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.global.BaseFragment;
import com.epfresh.api.global.BuyerConstant;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.JsonUtils;
import com.epfresh.api.utils.LocalDisplay;
import com.epfresh.api.utils.T;
import com.epfresh.api.widget.Dialog.BaseDialogView;
import com.epfresh.api.widget.ptr.PtrDefaultHandler;
import com.epfresh.api.widget.ptr.PtrFrameLayout;
import com.epfresh.api.widget.ptr.PtrHandler;
import com.epfresh.supplier.R;
import com.epfresh.supplier.activity.*;
import com.epfresh.supplier.adapter.*;
import com.epfresh.supplier.constant.Constant;
import com.epfresh.supplier.dialog.*;
import com.epfresh.supplier.entity.BuyerFilter;
import com.epfresh.supplier.entity.ContentEntity;
import com.epfresh.supplier.entity.BaseStoreListBean;
import com.epfresh.supplier.entity.HomeBuyer;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

import multitype.MultiTypeAdapter;
import multitype.OnRecyclerViewItemClickListener;
import multitype.loadmore.LoadMoreDelegate;
import multitype.loadmore.LoadMoreItem;
import multitype.loadmore.LoadMoreViewBinder;

/**
 * Created by zzq on 2017/12/4.
 */
public class AgentMakeFragment extends BaseFragment implements FilterCityDialog.SelectCondition{

    //列表数据
    List<Object> mItems = new ArrayList<>();
    MultiTypeAdapter mMultiAdapter;
    AgentMakeBaseGoodsViewBinder itemViewBinder;
    AgentMakeBaseTitleViewBinder titleViewBinder;
    GridLayoutManager mManager;
    RecyclerView rv;


    int pageNum = 0;
    private View llTitle,llCity,llCategory;
    private TextView tvCity,tvCategory;
    private ImageView ivCategory,ivCity;
    private int ivSelectFlag;//0,1,2 未出现dialog；city；category

    private int mSuspensionPosition = 1;

    private int dialogHeight =   LocalDisplay.dp2px(87);
    public static boolean isCanRefresh = true;


    LoadMoreDelegate loadMoreDelegate = new LoadMoreDelegate();
    private LoadMoreDelegate.LoadMoreSubject loadMoreSubject = new LoadMoreDelegate.LoadMoreSubject() {
        @Override
        public boolean canLoad() {
            return !ptrFrameLayout.isRefreshing();
        }

        @Override
        public void onLoadMore() {
            loadMoreDelegate.setStatusLoading();
            reqSupplyStoreDyn(pageNum + 1);
        }
    };

    @Override
    public void selectCity(String condition,String name) {
//        cityId = condition;
//        cityName = name;
//        reqSupplyStoreDyn(0);
//        commonDismiss();
    }

    @Override
    public void selectCategory(String condition,String name) {
//        categoryiiiId = condition;
//        categoryName = name;
//        reqSupplyStoreDyn(0);
//        commonDismiss();
    }


    @Override
    public String getBaseTag() {
        return Constant.TAG_HOME_FRAGMENT;
    }



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_agent_make,
                container, false);
    }

    private PtrFrameLayout ptrFrameLayout;
    private PtrHandler ptrHandler = new PtrHandler() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
            return PtrDefaultHandler.checkContentCanBePulledDown(frame, rv, header) && isCanRefresh;
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout frame) {
            reqSupplyStoreDyn(0);
//            reqFilter();
        }
    };

    private void initHeadView(View v) {
        ptrFrameLayout = (PtrFrameLayout) v.findViewById(R.id.fragment_ptr_home_ptr_frame);
        ptrFrameLayout.setPtrHandler(ptrHandler);
    }

    @Override
    public void onViewCreated(View v, Bundle savedInstanceState) {
        super.onViewCreated(v, savedInstanceState);
        initHeadView(v);
        rv = v.findViewById(R.id.rv_make_agent);
//        llCategory = v.findViewById(R.id.ll_make_agent_category);
//        llCity = v.findViewById(R.id.ll_make_agent_city);
//        llCity.setOnClickListener(this);
//        llCategory.setOnClickListener(this);
//        tvCity = v.findViewById(R.id.tv_city);
//        tvCategory = v.findViewById(R.id.tv_category);
//        ivCategory = v.findViewById(R.id.iv_category);
//        ivCity = v.findViewById(R.id.iv_city);
        mManager = new GridLayoutManager(getContext(), 3);
        GridLayoutManager.SpanSizeLookup spanSizeLookup = new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                Object item = mItems.get(position);
                return (item instanceof BaseStoreListBean.ProductsBean) ? 1 : 3;
            }
        };
        mManager.setSpanSizeLookup(spanSizeLookup);
        rv.setLayoutManager(mManager);
        mMultiAdapter = new MultiTypeAdapter();
        LoadMoreViewBinder loadMoreViewBinder = loadMoreDelegate.getLoadMoreViewBinder();
        loadMoreDelegate.attach(rv, loadMoreSubject);
        itemViewBinder = new AgentMakeBaseGoodsViewBinder();
        itemViewBinder.setOnRecyclerViewItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position, Object data) {
                if(data instanceof BaseStoreListBean.ProductsBean && mBaseStores!=null){
                    for(int i=0;i<mBaseStores.size();i++){
                        if(mBaseStores.get(i).getProducts().contains(data)){
                            intoProductDetail(mBaseStores.get(i).getId(),((BaseStoreListBean.ProductsBean)data).getId());
                            return;
                        }
                    }
                }
            }
        });
        titleViewBinder = new AgentMakeBaseTitleViewBinder();
        titleViewBinder.setOnRecyclerViewItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position, Object data) {
                if (data instanceof String) {
                    String id = (String) data;
                    Intent intent;
                    switch (view.getId()) {
                        case R.id.tv_make_agent_go:
                            String s = ((TextView)view).getText().toString();
                            if (s.equals("申请代办") || s.equals("重新申请")) {
                                SharedPreferences sp = getContext().getSharedPreferences("cache_config", Context.MODE_PRIVATE);
                                boolean isRead = sp.getBoolean("config_read_agent_notice"+"_"+ ApplicationHelper.getInstance().getUser().getAccountId()+"_"+ BaseApplication.getInstance().getMerchantId(), false);

                                if (!isRead) {
                                    //第一次跳转协议界面
                                    intent = new Intent(getContext(),WebAgentNoticeActivity.class);
                                    intent.putExtra("baseStoreId", id);
                                    intent.putExtra(Constant.KEY_WEB_URL, com.epfresh.api.constant.Constant.URL_HELP_AGENT_NOTICE);
                                    startActivity(intent);
                                } else {
                                    //非第一次进入申请资料界面
                                    intent = new Intent(getContext(),ApplyInfoActivity.class);
                                    intent.putExtra("baseStoreId",id);
                                    startActivity(intent);
                                }
                                return;
                            }
                            if (s.equals("申请中")) {
                                intent = new Intent(getContext(),ApplyInfoActivity.class);
                                intent.putExtra("daibanzhong","代办中");
                                intent.putExtra("baseStoreId",id);
                                startActivity(intent);
                                return;
                            }
                            if (s.equals("代办中")) {
                                intent = new Intent(getContext(), AgentMoneyDetailActivity.class);
                                intent.putExtra("baseStoreId", id);
                                startActivity(intent);
                                return;
                            }
                            if (s.equals("解除中")) {

                            }
//                            Toast.makeText(getContext(), s, Toast.LENGTH_SHORT).show();

//                            intent = new Intent(getContext(), BaseStoreInfoActivity.class);
//                            intent.putExtra("baseStoreId", id);
//                            intent.putExtra("mHasAgent",false);
//                            startActivity(intent);
                            break;
                        case R.id.tv_make_agent_detail:
                            intent = new Intent(getContext(), AgentMoneyDetailActivity.class);
                            intent.putExtra("baseStoreId", id);
                            startActivity(intent);
                            break;
                        case R.id.tv_make_agent_title:
                            intent = new Intent(getContext(), BaseStoreInfoActivity.class);
                            intent.putExtra("baseStoreId", id);
                            intent.putExtra("mHasAgent",false);
                            startActivity(intent);
                            break;
                    }
                }
            }
        });

        mMultiAdapter.register(BaseStoreListBean.class,titleViewBinder);
        mMultiAdapter.register(LoadMoreItem.class, loadMoreViewBinder);
        mMultiAdapter.register(BaseStoreListBean.ProductsBean.class,itemViewBinder);
        rv.setAdapter(mMultiAdapter);
        mMultiAdapter.setItems(mItems);
        rv.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
//                commonDismiss();
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
//                commonDismiss();
            }
        });
        reqSupplyStoreDyn(pageNum);
//        reqFilter();
    }

    private void intoProductDetail(String storeId, String id) {
        Intent intent = new Intent(getContext(), BaseProductDetailActivity.class);
        Log.e("6_________","___________");

        intent.putExtra("baseStoreId", storeId);
        intent.putExtra("productId", id);
        startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
//        commonDismiss();
//        switch (v.getId()) {
//            case R.id.ll_make_agent_city:
//                openCityDialog(1);
//                break;
//            case R.id.ll_make_agent_category:
//                openCategoryDialog();
//                break;
//        }

    }

    FilterCityDialog filterCityDialog;
    private void openCityDialog(int position) {
        if(buyerFilter==null){
            T.toast("没有加载到筛选信息，请刷新后重试");
            return;
        }
        if (filterCityDialog == null) {
            filterCityDialog = new FilterCityDialog(getContext());
            filterCityDialog.setOnDismissListener(new BaseDialogView.OnDismissListener() {
                @Override
                public void onDismiss(Object o) {
                    tvCity.setTextColor(Color.parseColor("#434343"));
                    tvCity.setText(cityName);
                    ivCity.setImageResource(R.mipmap.select_down);
                    Log.e("cityDismiss","_____________");
                }
            });
            filterCityDialog.setSelectCondition(this);
            tvCity.setTextColor(Color.RED);
            ivCity.setImageResource(R.mipmap.select_up);
            filterCityDialog.show(buyerFilter.getCities(),dialogHeight);
        }else {
            if (filterCityDialog.isShowing()) {
                filterCityDialog.dismiss();
            } else {
                tvCity.setTextColor(Color.RED);
                ivCity.setImageResource(R.mipmap.select_up);
                filterCityDialog.show(buyerFilter.getCities(), dialogHeight);
            }
        }
    }

    public void commonDismiss(){
        if(filterCityDialog !=null)
            filterCityDialog.dismiss();
        if(filterCategoryDialog!=null)
            filterCategoryDialog.dismiss();
    }

    FilterCategoryDialog filterCategoryDialog;

    private void openCategoryDialog() {
        if(buyerFilter==null){
            T.toast("没有加载到筛选信息，请刷新后重试");
            return;
        }
        if (filterCategoryDialog == null) {
            filterCategoryDialog = new FilterCategoryDialog(getContext());
            filterCategoryDialog.setSelectCondition(this);
            filterCategoryDialog.setOnDismissListener(new BaseDialogView.OnDismissListener() {
                @Override
                public void onDismiss(Object o) {
                    tvCategory.setTextColor(Color.parseColor("#434343"));
                    tvCategory.setText(categoryName);
                    ivCategory.setImageResource(R.mipmap.select_down);
                }
            });
            tvCategory.setTextColor(Color.RED);
            ivCategory.setImageResource(R.mipmap.select_up);
            filterCategoryDialog.show(buyerFilter.getNames(),dialogHeight);
        }else {
            if (filterCategoryDialog.isShowing()) {
                filterCategoryDialog.dismiss();
            } else {
                tvCategory.setTextColor(Color.RED);
                ivCategory.setImageResource(R.mipmap.select_up);
                filterCategoryDialog.show(buyerFilter.getNames(), dialogHeight);
            }
        }
    }


    List<BaseStoreListBean> mBaseStores = new ArrayList<>();
    List<BaseStoreListBean> mBaseStoreAll = new ArrayList<>();

    public String cityId = "",cityName = "城市";
    public String categoryiiiId = "",categoryName = "品类";
    public void reqSupplyStoreDyn(int pageNum) {
        if (getActivity() == null){
            return;
        }

        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(BuyerConstant.CMD_BUYER_STORE_BASE_LIST);
        RequestEntityMapSupply.putParameter("agentStoreId", BaseApplication.getInstance().getStoreId());
        RequestEntityMapSupply.putParameter("cityId", cityId);
        RequestEntityMapSupply.putParameter("categoryiiiId", categoryiiiId);
        RequestEntityMapSupply.putParameter("pageNumber", pageNum);
        RequestEntityMapSupply.putParameter("pageSize", 15);
        Log.e("categoryiiiId","______"+categoryiiiId);
        requestBuyer(RequestEntityMapSupply, BuyerConstant.CMD_BUYER_STORE_BASE_LIST, onSupplyStoreDynRequestListener);
    }

    private OnRequestListener<ContentEntity<BaseStoreListBean>> onSupplyStoreDynRequestListener = new OnRequestListener<ContentEntity<BaseStoreListBean>>() {
        @Override
        public ContentEntity<BaseStoreListBean> jsonToObj(String responseStr) {
            return JsonUtils.fromJsonObject(responseStr, ContentEntity.class, BaseStoreListBean.class);

        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            if (getActivity() == null){
                return;
            }
            ptrFrameLayout.refreshComplete();

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            if (getActivity() == null){
                return;
            }
            ptrFrameLayout.refreshComplete();

        }

        @Override
        public void onStart(Object tag) {
        }

        @Override
        public void onResponse(ResponseEntity<ContentEntity<BaseStoreListBean>> response, Object tag) {
            if (getActivity() == null){
                return;
            }
            ptrFrameLayout.refreshComplete();
            ContentEntity<BaseStoreListBean> responseElement = response.getResponseElement();
            boolean last = responseElement.getLast();
            int number = responseElement.getNumber();
            List<BaseStoreListBean> content = responseElement.getContent();
            //第一页
            if (number == 0) {
                mBaseStores.clear();
                mBaseStoreAll.clear();
            }
            pageNum = number;
            if (content != null) {
                mBaseStores.addAll(content);
                mBaseStoreAll.addAll(content);
            }

            if(pageNum==0){
                mBaseStoreAll.clear();
                mItems.clear();
                for(int i=0;i<content.size();i++){
                    mItems.add(content.get(i));
                    mItems.addAll(content.get(i).getProducts());
                }
            }else{
                for(int i=0;i<content.size();i++){
                    mItems.add(content.get(i));
                    mItems.addAll(content.get(i).getProducts());
                }
            }
            if (mBaseStores.size() == 0) {
                loadMoreDelegate.setStatusEmpty();
                loadMoreDelegate.addLoadItemOnly(mItems);
            }else {
                //当产地名称最大字符填写，发布商品后，在批发端-我要买-做代办 下面，最后2行不应该再重复显示店铺名称信息
//                loadMoreDelegate.addAllItem(mItems, mBaseStoreAll);
                loadMoreDelegate.addLoadItemOnly(mItems);
                //最后一个
                if (last) {
                    loadMoreDelegate.setStatusNoMore();
                } else {
                    loadMoreDelegate.setStatusNormal();
                }
            }
            mMultiAdapter.notifyDataSetChanged();
        }
    };


    BuyerFilter buyerFilter;

    private void reqFilter() {
        if (getActivity() == null){
            return;
        }

        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(BuyerConstant.CMD_BUYER_HOMEPAGE_FILTERS);
        RequestEntityMapSupply.putParameter("agentStoreId", BaseApplication.getInstance().getStoreId());
        RequestEntityMapSupply.putParameter("all", 1);
        requestBuyer(RequestEntityMapSupply, BuyerConstant.CMD_BUYER_HOMEPAGE_FILTERS, onSupplyFilterRequestListener);
    }

    private OnRequestListener<BuyerFilter> onSupplyFilterRequestListener = new OnRequestListener<BuyerFilter>() {
        @Override
        public BuyerFilter jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, BuyerFilter.class);
        }
        @Override
        public void onFail(int failCode, Object arg, Object tag) {
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
        }

        @Override
        public void onStart(Object tag) {
        }

        @Override
        public void onResponse(ResponseEntity<BuyerFilter> response, Object tag) {
            if (getActivity() == null){
                return;
            }
            buyerFilter = response.getResponseElement();

            //本地手动添加城市"全部"选项的假数据
            BuyerFilter.CitiesBean citiesBean = new BuyerFilter.CitiesBean();
            citiesBean.setCode("");
            citiesBean.setName("全部");
            citiesBean.setSelectFlag(false);
            buyerFilter.getCities().add(0,citiesBean);

            //手动添加品类"全部"选项假数据
            BuyerFilter.NamesBean namesBean = new BuyerFilter.NamesBean();
            namesBean.setName("");
            namesBean.setId("");

            List<BuyerFilter.NamesBean.ChildBean> child = new ArrayList<>();
            BuyerFilter.NamesBean.ChildBean childBean = new BuyerFilter.NamesBean.ChildBean();
            childBean.setId("");
            childBean.setName("全部");
            childBean.setSelectFlag(false);
            child.add(childBean);

            namesBean.setChild(child);
            buyerFilter.getNames().add(0,namesBean);

        }
    };


}
